import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-03-05
 * Time: 19:56
 */
public class IODemo14 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜素的单词");
        String word = scanner.nextLine();
        System.out.println("请输入搜索路径");
        String rootPath = scanner.nextLine();
        //判断路径的合法性
        File rootFile = new File(rootPath);
        if(!rootFile.isDirectory()) {
            System.out.println("路径不合法");
            return;
        }
        //遍历搜索目录的全部文件
        scanDir(rootFile, word);
    }
    private static void scanDir(File rootFile, String word) {
        File[] files = rootFile.listFiles();
        if(files == null) {
            return;
        }
        for(File f : files) {
            System.out.println("当前遍历到：" + f.getAbsolutePath());
            if(f.isFile()) {
                //搜索该文件是否有要查找的单词
                searchInFile(f, word);
            } else if(f.isDirectory()) {
                scanDir(f, word);
            } else {
                //不做处理
            }
        }
    }
    private static void searchInFile(File f, String word) {
        try(InputStream inputStream = new FileInputStream(f)) {
            StringBuilder stringBuilder = new StringBuilder();
            while (true) {
                byte[] buffer = new byte[1024];
                int n = inputStream.read(buffer);
                if(n == -1) {
                    break;
                }
                String s = new String(buffer, 0, n);
                stringBuilder.append(s);
            }
            //System.out.println("日志，当前读到文本的内容："  + stringBuilder);
            if(stringBuilder.indexOf(word) == -1) {
                return;
            }
            System.out.println("搜存的单词：" + word + " 存在于：" + f.getAbsolutePath());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
